package com.jsyso.weixin.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jsyso.jsyso.cache.Cache;
import com.jsyso.jsyso.cache.Element;
import com.jsyso.jsyso.cache.LazyCache;
import com.jsyso.jsyso.lang.JStringUtils;
import com.jsyso.jsyso.util.JsMap;
import com.jsyso.weixin.utils.Params;
import com.jsyso.weixin.web.InitParams;

/**
 * 认证并获取 access_token API
 * @author janjan, xujian_jason@163.com
 *
 */
public class AccessTokenAPI extends API {
	private static final Logger log = LoggerFactory.getLogger(AccessTokenAPI.class);
	private static Cache cache = new LazyCache();
	protected static final String TOKEN = "/cgi-bin/token";
	
	/**
	 * 通过appid获取access_token
	 * @param appid
	 * @return
	 */
	public static JsMap getAccessToken(String appid) {
		Response response = cache.get(Element.create(appid));
		// 如果缓存失效，则从新获取
		if(response == null) {
			AccessTokenAPI tokenAPI = new AccessTokenAPI();
			response = tokenAPI.token(Params.create("appid", appid).put("secret", InitParams.getConfig(appid, "appSecret"))).get();
			if(response != null && response.isSuccess()) {
				Integer expiresIn = response.get("expires_in", Integer.class);
				cache.put(Element.create(appid, response).setSeconds(expiresIn == null ? 7100 : expiresIn - 100));
			}
		}
		if(log.isDebugEnabled()) {
			log.debug("[获取access_token]response = " + (response == null ? "空" : response.toString()));
		}
		return response != null ? response.getAttrs() : null;
	}
	
	/**
	 * 获取新的access_token
	 * @param params
	 * @return
	 */
	public synchronized API token(Params params) {
		this.getParams = params.put("grant_type", "client_credential");
		this.url = JStringUtils.newBuilder(API_WEIXIN_QQ_COM, TOKEN).toString();
		return this;
	}
	
}
